import random
import string
import datetime
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.core.cache import cache
from django.conf import settings

def generate_verification_code(length=4):
    """生成随机验证码"""
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))

def generate_verification_code_image(code, width=120, height=40):
    """生成验证码图片"""
    # 创建一个白色背景的图片
    image = Image.new('RGB', (width, height), (255, 255, 255))
    # 创建Font对象
    try:
        font = ImageFont.truetype('arial.ttf', 30)
    except IOError:
        font = ImageFont.load_default()
    # 创建Draw对象
    draw = ImageDraw.Draw(image)
    # 填充随机颜色的小点
    for i in range(random.randint(50, 100)):
        draw.point(
            (random.randint(0, width), random.randint(0, height)),
            fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        )
    # 填充随机颜色的线条
    for i in range(random.randint(3, 5)):
        draw.line(
            [
                (random.randint(0, width), random.randint(0, height)),
                (random.randint(0, width), random.randint(0, height))
            ],
            fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
            width=1
        )
    # 计算文字位置
    left, top, right, bottom = draw.textbbox((0, 0), code, font=font)
    text_width = right - left
    text_height = bottom - top
    position = ((width - text_width) // 2, (height - text_height) // 2)
    # 填充文字
    for i in range(len(code)):
        draw.text(
            (position[0] + i * text_width // len(code), position[1] + random.randint(-5, 5)),
            code[i],
            font=font,
            fill=(random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))
        )
    # 模糊处理
    # image = image.filter(ImageFilter.BLUR)
    # 返回图片
    buf = BytesIO()
    image.save(buf, 'png')
    return buf.getvalue()

def save_verification_code_to_cache(request, code, timeout=300):
    """保存验证码到缓存"""
    session_key = request.session.session_key
    if not session_key:
        request.session.save()
        session_key = request.session.session_key
    cache_key = f'verification_code_{session_key}'
    cache.set(cache_key, code.upper(), timeout)
    return cache_key

def verify_code(request, user_input):
    """验证用户输入的验证码"""
    session_key = request.session.session_key
    if not session_key:
        return False
    cache_key = f'verification_code_{session_key}'
    code = cache.get(cache_key)
    if not code:
        return False
    # 验证后删除缓存
    cache.delete(cache_key)
    return code == user_input.upper() 